define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'order/main/index',
                    add_url: 'order/main/add',
                    edit_url: 'order/main/edit',
                    del_url: 'order/main/del',
                    designate_url: 'order/main/designate',
                    feedback_url: 'order/main/feedback',
                    mobile_url: 'order/main/mobile',
                    flag_url: 'order/main/flag',
                    complete_url: 'order/main/complete',
                    voucher_url: 'order/main/voucher',
                    cancel_url: 'order/main/cancel',
                    multi_url: 'order/main/multi',
                    import_url: 'order/main/import',
                    table: 'order_main',
                }
            });

            var table = $("#table");
            var isCompany = Config.isCompany;
            var isAttache = Config.isAttache;
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                search: false, //是否启用快速搜索
                columns: [
                    [
                        {checkbox: true},
                        !isCompany ? {
                            field: 'button',
                            width: "120px",
                            title: __('操作'),
                            table: table,
                            operate: false,
                            events: Table.api.events.buttons,
                            buttons: [
                                {
                                    name: 'flag',
                                    text: '标记',
                                    title: __('标记'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-flag',

                                    url: $.fn.bootstrapTable.defaults.extend.flag_url,
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        if (row.status == 4) {
                                            return false;
                                        }else{
                                            return true;
                                        }
                                    },
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    }
                                },
                                {
                                    name: 'mobile',
                                    text: '师傅电话',
                                    title: __('上传师傅电话'),
                                    classname: 'btn btn-xs btn-primary btn-dialog',

                                    url: $.fn.bootstrapTable.defaults.extend.mobile_url,
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        if (row.status == 4) {
                                            return false;
                                        }else{
                                            return true;
                                        }
                                    },
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    }
                                },
                                {
                                    name: 'complete',
                                    text: '完成照片',
                                    title: __('上传完成照片'),
                                    classname: 'btn btn-xs btn-primary btn-dialog',

                                    url: $.fn.bootstrapTable.defaults.extend.complete_url,
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        if (row.status == 4) {
                                            return false;
                                        }else{
                                            return true;
                                        }
                                    },
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    }
                                },
                                {
                                    name: 'voucher',
                                    text: '收款凭证',
                                    title: __('上传收款凭证'),
                                    classname: 'btn btn-xs btn-primary btn-dialog',

                                    url: $.fn.bootstrapTable.defaults.extend.voucher_url,
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        if (row.status == 4) {
                                            return false;
                                        }else{
                                            return true;
                                        }
                                    },
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    }
                                },
                            ],
                            formatter: Table.api.formatter.buttons
                        }:{
                            field: '',
                            visible: false
                        },
                        {field: 'code', title: __('Code')},
                        {field: 'attribute.category.myPid.myPid.title', title: __('一级品类'), operate: false},
                        {
                            field: 'category_first_id',
                            title: __('一级品类'),
                            visible: false,
                            searchList: $.getJSON("order/category/jsonList")
                        },
                        {field: 'attribute.category.myPid.title', title: __('二级品类'), operate: false},
                        {field: 'attribute.category.title', title: __('三级品类'), operate: false},
                        {field: 'admin.company.id', title: __('厂商ID')},
                        {field: 'admin.company.title', title: __('Admin_id'), operate: false},

                        {field: 'quantity', title: __('Quantity'), operate: false},
                        isCompany || !isAttache ? {field: 'price', title: __('Price'), operate: 'BETWEEN'} : {
                            field: '',
                            visible: false
                        },
                        {
                            field: 'admin_id',
                            title: __('Admin_id'),
                            visible: false,
                            searchList: $.getJSON("auth/admin/companyList")
                        },
                        {field: 'attache.nickname', title: __('Attache_id'), operate: false},
                        {
                            field: 'attache_id',
                            title: __('Attache_id'),
                            visible: false,
                            searchList: $.getJSON("auth/admin/attacheList")
                        },
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'tel', title: __('Tel')},
                        {field: 'mobile', title: __('师傅电话'), operate: false},
                        {field: 'province.name', title: __('Province'), operate: false},
                        {field: 'city.name', title: __('City'), operate: false},
                        {field: 'country.name', title: __('Country'), operate: false},


                        {field: 'address', title: __('Address'), operate: false},
                        {field: 'remark', title: __('Remark'), operate: 'LIKE'},
                        {field: 'trademark.title', title: __('Trademark_id'), operate: false},
                        !isCompany ?{field: 'attribute.title', title: __('Attribute_id'), operate: false}:{field: '', visible: false},
                        {field: 'admin.company.technology', title: __('技术电话'), operate: false},
                        {
                            field: 'trademark_id',
                            title: __('Trademark_id'),
                            visible: false,
                            searchList: $.getJSON("order/trademark/jsonList")
                        },
                        {field: 'service_time', title: __('Service_time'), operate: 'RANGE', addclass: 'datetimerange'},
                        {field: 'create_time', title: __('Create_time'), operate: 'RANGE', addclass: 'datetimerange'},
                        {
                            field: 'designate_time',
                            title: __('Designate_time'),
                            operate: 'RANGE',
                            addclass: 'datetimerange'
                        },
                        {
                            field: 'complete_time',
                            title: __('Complete_time'),
                            operate: 'RANGE',
                            addclass: 'datetimerange'
                        },
                        !isCompany ?{
                            field: 'images', 
                            title: __('Images'), 
                            visible: false,
                            formatter: Table.api.formatter.images, 
                            operate: false
                        }:{
                            field: 'images', 
                            title: __('Images'), 
                            formatter: Table.api.formatter.images, 
                            operate: false
                        },
                        !isCompany ?{
                            field: 'feedback_images',
                            title: __('Feedback_images'),
                            visible: false,
                            formatter: Table.api.formatter.images,
                            operate: false
                        }:{
                            field: 'feedback_images',
                            title: __('Feedback_images'),
                            formatter: Table.api.formatter.images,
                            operate: false
                        },
                        {field: 'feedback_content', title: __('Feedback_content'), operate: false},
                        !isCompany ? {
                            field: 'flag',
                            title: __('Flag'),
                            operate: '=',
                            searchList: {"1": '未标记', "2": '已标记'}
                        } : {field: '', visible: false},
                        !isCompany ? {
                            field: 'voucher',
                            title: __('Voucher'),
                            formatter: Table.api.formatter.images,
                            operate: false,
                            visible: false,
                        } : {field: '', visible: false},
                        !isCompany ? {
                            field: 'voucher_content',
                            title: __('Voucher Content'),
                        } : {field: '', visible: false},
                        {
                            field: 'status',
                            title: __('Status'),
                            searchList: {
                                "2": __('Status 2'),
                                "3": __('Status 3'),
                                "4": __('Status 4'),
                                "5": __('Status 5')
                            },
                            formatter: Table.api.formatter.status
                        },
                        {
                            field: 'operate',
                            width: "120px",
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [

                                {
                                    name: 'feedback',
                                    text: '反馈信息',
                                    title: __('反馈信息'),
                                    classname: 'btn btn-xs btn-primary btn-dialog',

                                    url: $.fn.bootstrapTable.defaults.extend.feedback_url,
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        if (row.status == 4) {
                                            return false;
                                        }else{
                                            return true;
                                        }
                                    },
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    }
                                },
                                {
                                    name: 'cancel',
                                    text: '取消订单',
                                    title: __('取消订单'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-cancel',

                                    url: $.fn.bootstrapTable.defaults.extend.cancel_url,
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        if (row.status == 4) {
                                            return false;
                                        }else{
                                            return true;
                                        }
                                    },
                                    callback: function (data) {
//                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    }
                                },
                            ],
                            formatter: Table.api.formatter.operate
                        },
                    ]
                ]
            });


            // // 绑定TAB事件
            // $('.panel-heading a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
            //     var field = $(this).closest("ul").data("field");
            //     var value = $(this).data("value");
            //     var options = table.bootstrapTable('getOptions');
            //     options.pageNumber = 1;
            //     options.queryParams = function (params) {
            //         var filter = {};
            //         if (value !== '') {
            //             filter[field] = value;
            //         }
            //         params.filter = JSON.stringify(filter);
            //         return params;
            //     };
            //     table.bootstrapTable('refresh', {});
            //     return false;
            // });
            //当表格数据加载完成时
            table.on('load-success.bs.table', function (e, data) {
                //这里可以获取从服务端获取的JSON数据

                //这里我们手动设置底部的值
                if (Config.isCompany) {
                    $(".total_money").hide();
                }
                if (Config.isAttache) {
                    $(".total_price").hide();
                }
                $("#total_price").text(data.total_price);
                $("#total_money").text(data.total_money);

            });
            // 绑定TAB事件
            $('.panel-heading a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var field = $(this).closest("ul").data("field");
                var value = $(this).data("value");
                var options = table.bootstrapTable('getOptions');
                options.pageNumber = 1;
                var queryParams = options.queryParams;
                options.queryParams = function (params) {
                    console.log(params);
                    var params = queryParams(params);
                    var filter = params.filter ? JSON.parse(params.filter) : {};
                    if (value !== '') {
                        filter[field] = value;
                    } else {
                        delete filter[field];
                    }
                    params.filter = JSON.stringify(filter);
                    return params;
                };
                table.bootstrapTable('refresh', {});
                return false;
            });

            $(document).on("click", ".btn-cancel", function (e) {
                e.stopPropagation();
                e.preventDefault();
                var index = $(this).data('rowIndex');
                var row = Table.api.getrowbyindex(table, index);
                var that = this;
                var top = $(that).offset().top - $(window).scrollTop();
                var left = $(that).offset().left - $(window).scrollLeft() - 260;
                if (top + 154 > $(window).height()) {
                    top = top - 154;
                }
                if ($(window).width() < 480) {
                    top = left = undefined;
                }
                Layer.confirm(
                    __('确定要取消订单?(说明：未完成订单金额将退还给厂商。)'),
                    {icon: 3, title: __('Warning'), offset: [top, left], shadeClose: true},
                    function (index) {
                        var table = $(that).closest('table');
                        var options = table.bootstrapTable('getOptions');
                        Table.api.cancel("cancel", row[options.pk], table, that);
                        Layer.close(index);
                    }
                );
            });
            //标记订单
            $(document).on("click", ".btn-flag", function (e) {
                e.stopPropagation();
                e.preventDefault();
                var index = $(this).data('rowIndex');
                var row = Table.api.getrowbyindex(table, index);
                var that = this;
                var top = $(that).offset().top - $(window).scrollTop();
                var left = $(that).offset().left - $(window).scrollLeft() - 260;
                if (left<0) left += 280;
                if (top + 154 > $(window).height()) {
                    top = top - 154;
                }
                if ($(window).width() < 480) {
                    top = left = undefined;
                }
                Layer.confirm(
                    __('确定要标记订单？'),
                    {icon: 3, title: __('Warning'), offset: [top, left], shadeClose: true},
                    function (index) {
                        var table = $(that).closest('table');
                        var options = table.bootstrapTable('getOptions');
                        Table.api.flag("flag", row[options.pk], table, that);
                        Layer.close(index);
                    }
                );
            });
            // 获取选中项
            $(document).on("click", ".btn-selected", function () {
                var ids = Table.api.selectedids(table);
//                console.log(ids);
                var url = $.fn.bootstrapTable.defaults.extend.designate_url;
                url = Table.api.replaceurl(url, {ids: ids}, table);
                Fast.api.open(url, "批量指派订单", $(this).data() || {});
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            $('textarea[name="textarea').change(function (e) {
                Fast.api.ajax({
                    url: 'ajax/addressResolve',
                    data: {text: $(this).val()}
                }, function (data, ret) {
                    //成功的回调
//                    console.log(data);
                    $('select[name="province"]').attr('data-value', data.province);
                    $('select[name="city"]').attr('data-value', data.city);
                    $('select[name="area"]').attr('data-value', data.area);
                    $('select[name="province"]').val(data.province);
                    $('select[name="city"]').val(data.city);
                    $('select[name="area"]').val(data.area);
                    $("select[name='province']").trigger("change");
                    $('input[name="row[name]"]').val(data.name);
                    $('input[name="row[tel]"]').val(data.tel);
                    $('input[name="row[address]"]').val(data.address);
                    $('textarea[name="row[remark]"]').val(data.remark);
                    return false;
                }, function (data, ret) {
                    //失败的回调
                    return false;
                });
            });
            $('.submit').submit(function (e) {
                e.preventDefault();
                alert("Submit prevented")
            });
            $("#c-trademark_id").data("params", function (obj) {
                return {custom: {admin_id: $("#c-admin_id").val()}};
            });
        },
        edit: function () {
            Controller.api.bindevent();

        },
        designate: function () {
            Controller.api.bindevent();
        },
        complete: function () {
            Controller.api.bindevent();
        },
        voucher: function () {
            Controller.api.bindevent();
        },
        feedback: function () {
            Controller.api.bindevent();
        },
        mobile: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});